package nkr1pt.popkorn;

import nkr1pt.popkorn.interact.Interactor;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.net.URL;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import nkr1pt.popkorn.exceptions.ExceptionHandler;
import nkr1pt.popkorn.exceptions.RecoverableException;
import nkr1pt.popkorn.exceptions.UnrecoverableException;
import nkr1pt.popkorn.guice.PopkornModule;
import nkr1pt.popkorn.helper.PathWatcher;
import nkr1pt.popkorn.properties.PropertyFileWatcher;
import nkr1pt.popkorn.properties.PropertyLoader;
import nkr1pt.popkorn.schedule.DownloadScheduler;
import org.apache.log4j.PropertyConfigurator;

/**
 * Main class which bootstraps the Popkorn application.
 *
 */
public class Main {

    private static final Logger logger = Logger.getLogger(Main.class.getName());

    public static void main(String[] args) {
        final ExceptionHandler exceptionHandler = new ExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

            public void uncaughtException(Thread t, Throwable e) {
                exceptionHandler.handleException(e);
            }
        });

        URL log4jProps = ClassLoader.getSystemResource("log4j.properties");
        PropertyConfigurator.configure(log4jProps);

        Injector injector = Guice.createInjector(new PopkornModule());

        PropertyFileWatcher propertyFileWatcher = injector.getInstance(PropertyFileWatcher.class);
        Timer propertyFileWatcherTimer = new Timer("PropertyFileWatcherTimer");
        propertyFileWatcherTimer.schedule(propertyFileWatcher, 0, 5000);

        PathWatcher downloadCandidatesWatcher = injector.getInstance(PathWatcher.class);
        downloadCandidatesWatcher.setPath(injector.getInstance(PropertyLoader.class).getProperties().getDownloadCandidates());
        Timer downloadCandidatesWatcherTimer = new Timer("DownloadCandidatesWatcherTimer");
        downloadCandidatesWatcherTimer.schedule(downloadCandidatesWatcher, 0, 5000);

        Interactor interactor = injector.getInstance(Interactor.class);
        interactor.start();

        DownloadScheduler downloadScheduler = injector.getInstance(DownloadScheduler.class);
        downloadScheduler.scheduleDownloads();
    }
}